package es.xpt.ysf.commons.jcr.view;


import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import javax.faces.context.FacesContext;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.PathNotFoundException;
import javax.jcr.Repository;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.SimpleCredentials;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.myfaces.custom.fileupload.UploadedFile;

import es.xpt.ysf.commons.jcr.ImageWrapper;
import es.xpt.ysf.commons.jcr.JcrNodeInfo;
import es.xpt.ysf.dao.DAOUtils;
import es.xpt.ysf.jaas.YSFPrincipal;
import es.xpt.ysf.logging.LogManager;
import es.xpt.ysf.view.Controller;
import es.xpt.ysf.view.model.UserBean;
import es.xpt.ysf.web.Constants;

@SuppressWarnings("serial")
public class AttachController extends Controller { // NO_UCD

	private UploadedFile upFile;
	private String name;
	private String path;
	private String entityId;
	private List<JcrNodeInfo> images;
	private TreeMap<String, String> otherDocsList;

	private String jcrDS = "java:jcr/local";
	private String uploadErrors="";
	

	private List<String> selectedNodes;
	

	public AttachController ()  {
		
	}
	
	public AttachController (String path, String entityId)  {
		this.path = path;
		this.entityId = entityId;
	}
	

	private Session init (YSFPrincipal principal) {
		
		UserBean user=null;
		
		if (principal==null) {
			HttpSession s = (HttpSession)FacesContext.getCurrentInstance().getExternalContext().getSession(false);
			if (s!=null) {
				user = (UserBean) s.getAttribute(Constants.USER_INFORMATION.getValue());
			}
		}
		if (user!=null)
			setJcrDS(DAOUtils.getJcrDsJndiName(user.getPrincipal()));
		else setJcrDS(DAOUtils.getJcrDsJndiName(principal));
		
		try {
			InitialContext ctx = new InitialContext();
			Repository repo = (Repository) ctx.lookup(getJcrDS());
			return repo.login(new SimpleCredentials("username", "password".toCharArray()));
		} catch (NamingException e) {
			LogManager.getLog(getClass()).error(e.getMessage(), e);
			return null;
		} catch (RepositoryException e) {
			LogManager.getLog(getClass()).error(e.getMessage(), e);
			return null;
		}
	}
		
	public void setImages(List<JcrNodeInfo> images) {
		this.images = images;
	}

	/**
	private void lista(String type, Node root, String productType, Session s) throws RepositoryException {
		System.err.println("TTTTTTIPO " + type );
		try {
            Node images = root.getNode( type); //product/LODGING/prueba/images
            NodeIterator ni = images.getNodes();
            while (ni.hasNext()) {
            	Node n = ni.nextNode();
            	System.err.println(n);
            	String mipath = n.getPath().replace("/default", "default") + "/images";
            	Node images2 = root.getNode(mipath);
            	NodeIterator ni2 = images2.getNodes(); 
            	
            	while ( ni2.hasNext() ) {
            		Node n2 = ni2.nextNode();
            		System.err.println(n2);
            		String fileName = n2.getPath(); 
            		fileName = fileName.substring(fileName.lastIndexOf('\\')+1);
                    fileName = fileName.substring(fileName.lastIndexOf('/')+1);
                    
            		miupload ( mipath, productType, n2.getNode("jcr:content").getProperty("jcr:data").getStream(), 
            				n2.getNode("jcr:content").getProperty("jcr:mimeType").getString(), fileName );
            	}
            	
            	//imagesList.put(n.getNode("jcr:content").getUUID(), n.getName());
            }
        } catch (PathNotFoundException e) {
        	LogManager.getLog(getClass()).error(e.getMessage(), e);
        }
	}
	
	private void miupload(String mipath, String productType, InputStream inputStream, String contentType, String fileName) {
		Session s = null;
		try {
			InitialContext ctx = new InitialContext() ;
			
	        Repository repo = (Repository) ctx.lookup("java:jcr/aramon2");
	        s = repo.login(new SimpleCredentials("username", "password".toCharArray())) ;
            Node root = s.getRootNode();
            
            Node type = root.getNode("default/enumValue"); //product/LODGING
            
            
            
            Node folderNode;
            try {
            	folderNode = root.getNode( mipath ); // type.getNode("product/LODGING/prueba/images");
            } catch (PathNotFoundException e) {
            	Node entity;
            	String mid = mipath.substring(mipath.indexOf("enumValue")+ 9+1, mipath.length()-7);
            	try {
            		entity = type.getNode(mid);
            	} catch (PathNotFoundException e2) {
            		entity = type.addNode(mid);
            	}
            	folderNode = entity.addNode("images", "nt:folder");
            }
            
            
            Node fileNode = folderNode.addNode(fileName, "nt:file");
            Node resNode = fileNode.addNode("jcr:content", "nt:resource");
    		resNode.setProperty("jcr:mimeType", contentType);
    		resNode.setProperty("jcr:encoding", "");
    		resNode.setProperty("jcr:data", inputStream);
    		Calendar lastModified = Calendar.getInstance();
    		resNode.setProperty("jcr:lastModified", lastModified);
    		//resNode.setProperty("tio:clientFileName", upFile.getName());
    		s.save();
    		
		} catch (Exception e) {
			LogManager.getLog(getClass()).error(e.getMessage(), e);
		} finally {
			if ( s!=null ) s.logout();
		}
	}
	
	public String listNodes() {
		Session s = null;
		try {
			InitialContext ctx = new InitialContext() ;
						
	        Repository repo = (Repository) ctx.lookup("java:jcr/aramon");
	        s = repo.login(new SimpleCredentials("username", "password".toCharArray())) ;
            
            Node root = s.getRootNode();
            
            lista ("default/enumValue", root, "LODGING", s);
//            lista ("default/product/SERVICE", root, "SERVICE",s );
//            lista ("default/product/HIGHLIGHT", root, "HIGHLIGHT",s);
                      
		} catch (Exception e) {
			LogManager.getLog(getClass()).error(e.getMessage(), e);
			
		} finally {
			if ( s!=null ) s.logout();
		}

		return "";
	}
	*/
	
	private void loadAttachs(YSFPrincipal principal) {
		Session s = null;
		try {
			if (principal!=null)
				s = init(principal);
			else
				s = init(null);
            
			if ( s==null )
				return ;
			
            Node root = s.getRootNode();
            try {
            	
	            Node imagesNode = root.getNode("default/" + path + "/" + entityId + "/images"); //product/LODGING/prueba/images
	            NodeIterator ni = imagesNode.getNodes();
	            images = new ArrayList<JcrNodeInfo>();
	            while (ni.hasNext()) {
	            	Node n = ni.nextNode();
	            	JcrNodeInfo jcrNodeInfo = new JcrNodeInfo();
	            	Node contentNode = n.getNode("jcr:content");
	            	jcrNodeInfo.setId(contentNode.getUUID());
	            	jcrNodeInfo.setName(n.getName());
	            	images.add(jcrNodeInfo);
	            	
	            	if (contentNode.hasProperty("ysf:order")){
	            		 jcrNodeInfo.setOrder(
	            				Integer.parseInt(contentNode.getProperty("ysf:order").getValue().getString()));
	            	}else{
	            		 jcrNodeInfo.setOrder(Integer.MAX_VALUE);
	            	}
	            }
            } catch (PathNotFoundException e) {
            	images = new ArrayList<JcrNodeInfo>(0);
            }
            Collections.sort(images);
            
            try {
	            Node otherDocs = root.getNode("default/" + path + "/" + entityId + "/otherDocs"); //product/LODGING/prueba/images
	            NodeIterator ni = otherDocs.getNodes();
	            otherDocsList = new TreeMap<String, String>();
	            while (ni.hasNext()) {
	            	Node n = ni.nextNode();
	            	otherDocsList.put(n.getNode("jcr:content").getUUID(), n.getName());
	            }
            } catch (PathNotFoundException e) {
            	otherDocsList = new TreeMap<String, String>();
            }
            
		} catch (RepositoryException e) {
			LogManager.getLog(getClass()).error(e.getMessage(), e);
			
		} finally {
			if ( s!=null ) s.logout();
		}
	}
	private void loadAttachs() {
		loadAttachs(null);
	}
	
	private void upload(String folder, TreeMap<String, String> list) throws IOException {
		Session s = null;
		try {
            s = init(null);
            if ( s == null )
            	return ;
            Node root = s.getRootNode();
            Node type = root.getNode("default/" + path); //product/LODGING
            
            Node folderNode;
            try {
            	folderNode = type.getNode( entityId + "/" + folder); // type.getNode("prueba/images");
            } catch (PathNotFoundException e) {
            	Node entity;
            	try {
            		entity = type.getNode(entityId);
            	} catch (PathNotFoundException e2) {
            		entity = type.addNode(entityId);
            	}
            	folderNode = entity.addNode(folder, "nt:folder");
            }
            String fileName = upFile.getName();
            fileName = fileName.substring(fileName.lastIndexOf('\\')+1);
            fileName = fileName.substring(fileName.lastIndexOf('/')+1);
                        
            Node fileNode = folderNode.addNode(fileName, "nt:file");
            Node resNode = fileNode.addNode("jcr:content", "nt:resource");
    		resNode.setProperty("jcr:mimeType", upFile.getContentType());
    		resNode.setProperty("jcr:encoding", "");
    		resNode.setProperty("jcr:data", upFile.getInputStream());
    		Calendar lastModified = Calendar.getInstance();
    		resNode.setProperty("jcr:lastModified", lastModified);
    		if (folder.equals("images")){
    			String order = "0";
    			if ( images == null ) {
    				order = getFollowingNumber(folderNode).toString();
    			} else if ( !images.isEmpty() ){
    				order = String.valueOf(images.get(images.size()-1).getOrder()+1);
    			}
    			resNode.addMixin("ysf:info");
    			resNode.setProperty("ysf:order", order);
    		}
    	
    		s.save();
    		if (folder.equals("otherDocs")){
    			if ( list== null ) { 
    				list = new TreeMap<String, String>();
    			}
    			list.put(resNode.getUUID(), fileName);
    		}
    		
		} catch (RepositoryException e) {
			LogManager.getLog(getClass()).error(e.getMessage(), e);
		} finally {
			if ( s!=null ) s.logout();
		}		
	}
	
	
	private Integer getFollowingNumber (Node images ){
		Integer number = -1;
		try{
			
	        NodeIterator ni = images.getNodes();
	        while (ni.hasNext()) {
	        	Node n = ni.nextNode();
	        	if (n.getNode("jcr:content").getProperty("ysf:order").getValue() != null){
	        		Integer order = Integer.parseInt(n.getNode("jcr:content").getProperty("ysf:order").getValue().getString());
	        		if (order > number){
	        			number = order;
	        		}
	        	}
	        }
		}catch (PathNotFoundException e) {
        	return 0;
        }catch (RepositoryException e) {
        	LogManager.getLog(getClass()).error(e.getMessage(), e);
        	return 0;
        } 
        return number + 1;
	}
	
	
	private Node getNodeCommon (Session s, Node node, boolean after){
		Node afterNode = null;
		Integer afterOrder = null;
		try{
			Integer nodeOrder = Integer.parseInt(node.getProperty("ysf:order").getValue().getString());
			Node root = s.getRootNode();
			Node images = root.getNode("default/" + path + "/" + entityId + "/images"); //product/LODGING/prueba/images    
	        NodeIterator ni = images.getNodes();   
	        while (ni.hasNext()) {
	        	Node n = ni.nextNode(); 
	        	if (n.getNode("jcr:content").hasProperty("ysf:order") &&
	        			!n.getNode("jcr:content").getUUID().equals(node.getUUID())){
	        		Integer nOrder = Integer.parseInt(n.getNode("jcr:content").getProperty("ysf:order").getValue().getString());
	        		if (after){
	        			if (nOrder > nodeOrder && (afterOrder == null || nOrder < afterOrder)){
	        				afterOrder = nOrder;
	        				afterNode = n;
	        			}
	        		}else{
	        			if (nOrder < nodeOrder && (afterOrder == null || nOrder > afterOrder)){
	        				afterOrder = nOrder;
	        				afterNode = n;
	        			}
	        		}
	        	}else{
	        		// No tiene orden !!!! 
	        		
	        	}
	        }
	        afterNode = afterNode.getNode("jcr:content");
		}catch (PathNotFoundException e) {
        	return null;
        }catch (RepositoryException e) {
        	LogManager.getLog(getClass()).error(e.getMessage(), e);
        	return null;
        } 
        return afterNode;
	}
	
	
	
	
	
	
	public String uploadOther()  {
		if ( path == null || path.trim().length()==0 ) {
			throw new NullPointerException("path");
		}
		if ( entityId == null || entityId.trim().length()==0 ) {
			throw new NullPointerException("entityId");
		}
		
		try {
			upload("otherDocs", otherDocsList);
			return "success";
		} catch (IOException e) {
			LogManager.getLog(getClass()).error(e.getMessage(), e);
			return "failure";
		}
		
    }
	
	public String uploadImage() {
		if ( path == null || path.trim().length()==0 ) {
			throw new NullPointerException("path");
		}
		if ( entityId == null || entityId.trim().length()==0 ) {
			throw new NullPointerException("entityId");
		}
		try {
			upload("images", null);
			loadAttachs();
			return "success";
		} catch (IOException e) {
			LogManager.getLog(getClass()).error(e.getMessage(), e);
			return "failure";
		}
		
    }
	
	
	public TreeMap<String, String> getOtherDocsList() {
		if ( images==null && otherDocsList==null ) {
			loadAttachs();
		}
		return otherDocsList;
	}
	
	private void remove (TreeMap<String, String> list) {
		Session s = null;
		try {
			s = init(null);
			
			if ( s==null )
				return ;
			
        	try {
        		s.getNodeByUUID(name).getParent().remove();
        	} catch (PathNotFoundException e2) { }
        	if ( list!=null )
        		list.remove(name);
	        
	        s.save();
                        
		} catch (RepositoryException e) {
			LogManager.getLog(getClass()).error(e.getMessage(), e);
			
		} finally {
			if ( s!=null ) s.logout();
		}
	}
	
	public String removeDoc() {
		remove( otherDocsList);
		return "success";
	}
	
	public String removeImage() {		
		remove(null);
		loadAttachs();
		return "success";
	}
	
	private void download ( InputStream fis, OutputStream os ) throws IOException {
		int read = 0;
		byte[] bytes = new byte[1024];
		while ((read = fis.read(bytes)) != -1) {
			os.write(bytes, 0, read);
		}
		os.flush();
	}
	
	private void responseError() {
		HttpServletResponse resp = (HttpServletResponse) getFacesContext().getExternalContext().getResponse();
		
		resp.setContentType("text/html");

        PrintWriter out = null;
        try {
            out=resp.getWriter();
        } catch (IOException io) {
        }
        
        out.println("<html>");
        out.println("<head>");
        out.println("<title>File not found</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<br><b>File not found</b>");
        out.println("</body>");
        out.println("</html>");

        out.flush();
        out.close();
        
        FacesContext.getCurrentInstance().responseComplete();
		
	}
	private void download(Node image, Float width, Float height) throws IOException, RepositoryException {
		HttpServletResponse response = (HttpServletResponse) getFacesContext().getExternalContext().getResponse();
		
		InputStream fis = null;
		OutputStream os = null;
		try {
			response.setContentType(image.getProperty("jcr:mimeType").getString());
			response.setHeader("Content-Disposition", "filename=\""
					+ image.getParent().getName() + "\"");
			
			fis = image.getProperty("jcr:data").getStream();
			if ( width!=null || height!=null ) {
				fis = ImageWrapper.convertToFormatRatio(fis, 
						image.getParent().getName(), image.getUUID(), 
						width!=null?width:0, height!=null?height:0);	
			}
			os = response.getOutputStream();
			download ( fis, os );
			
		} finally {
			if ( fis!=null ) {
				try {
					fis.close();
				} finally {
					if ( os!=null ) {
						os.close();
					}		
				}
			}
			
		}

		FacesContext.getCurrentInstance().responseComplete();
	}

	/**
	 * @param upLoadErrors the upLoadErrors to set
	 */
	public void setUploadErrors(String uploadErrors) {
		this.uploadErrors = uploadErrors;
	}
	
	public String getUploadErrors() {
		HttpServletRequest req = (HttpServletRequest) getFacesContext().getExternalContext().getRequest();
		String error = (String)req.getAttribute("org.apache.myfaces.custom.fileupload.exception");
		if (error!=null && !error.equals(""))
			setErrorMessage("uploadFile.sizeLimitExceeded");
		return uploadErrors;
	}
	
	private String getScaledImage(String uuid, String[] width, String[] height) {
		
		
		if ( width!=null || height!=null ) {
			File file = ImageWrapper.getFile(uuid, width!=null?Float.valueOf(width[0]):0, height!=null?Float.valueOf(height[0]):0);
			if (file.exists() && file.length() > 0 ) {
				HttpServletResponse response = (HttpServletResponse) getFacesContext().getExternalContext().getResponse();
				InputStream fis = null; 
				OutputStream os = null;
				try {
					fis = new FileInputStream(file);
					os = response.getOutputStream();
					download(fis, os);
				} catch (IOException e) {
					LogManager.getLog(getClass()).debug(e.getMessage(), e);
					return "failure";
				} finally {
					FacesContext.getCurrentInstance().responseComplete();
					if ( fis!=null ) {
						try {
							fis.close();
						} catch (IOException e) {
							
						} finally {
							if ( os!=null ) {
								try {
									os.close();
								} catch (IOException e) {
								}
							}		
						}
					}
				}

				return "success";
			}
		}
		return null;
	}
	
	public String download() {
		
		Map<String, String[]> params = getFacesContext().getExternalContext().getRequestParameterValuesMap();
		String[] width = params.get("width");
		String[] height = params.get("height");
		
		String result = getScaledImage(path, width, height);
		
		if ( result!=null && "success".equals(result) ) 
			return result;

		Session s = null;
		try {
			s = init(null);
			if ( s == null )
				return "failure";
			
			download(s.getNodeByUUID(path), width!=null?Float.valueOf(width[0]):null, height!=null?Float.valueOf(height[0]):null);
			return "success";
		} catch (IOException e) {
			LogManager.getLog(getClass()).debug(e.getMessage(), e);
			return "failure";
		} catch ( javax.jcr.ItemNotFoundException e ) {
			LogManager.getLog(getClass()).debug(e.getMessage(), e);
			return "failure";
		} catch ( javax.jcr.PathNotFoundException e ) {
			LogManager.getLog(getClass()).debug(e.getMessage(), e);
			return "failure";
		} catch (RepositoryException e) {
			LogManager.getLog(getClass()).debug(e.getMessage(), e);
			return "failure";
		} catch (Throwable e) {
			LogManager.getLog(getClass()).debug(e.getMessage(), e);
			return "failure";

		} finally {
			if (s != null)
				s.logout();
		}
	}

	
	private InputStream getFirstImageStream(String path, String namePattern) {

		Session s = null;
		InputStream fis = null;
		try {
			s = init(null);
			if ( s == null ) 
				return null;
			
            TreeMap<Integer, Node> orderImages = new TreeMap<Integer, Node> (); 
			List<Node> noOrderImages = new ArrayList<Node> ();
            Node root = s.getRootNode();
            Node images = root.getNode("default/" + path + "/images");
            NodeIterator ni = images.getNodes(namePattern);
            while (ni.hasNext()) {
            	Node image = ni.nextNode().getNode("jcr:content");
            	if ( image!=null ){
            		if (image.hasProperty("ysf:order")){
            			orderImages.put(Integer.parseInt(image.getProperty("ysf:order").getValue().getString()), image);
            		}else{
            			noOrderImages.add(image);
            		}
            		
            	}
            }
            if (!orderImages.isEmpty()){
            	fis = orderImages.firstEntry().getValue().getProperty("jcr:data").getStream();
            }else if (!noOrderImages.isEmpty()){
            	fis = noOrderImages.get(0).getProperty("jcr:data").getStream();
            }
		} catch (RepositoryException e) {
			LogManager.getLog(getClass()).debug(e.getMessage(), e);
		} finally {
			if (s != null)
				s.logout();
		}

		return fis;
	}
	
	public InputStream getFirstImageStream(String path, String namePattern, String defaultPattern)  {
		
		InputStream result = getFirstImageStream(path, namePattern);
		if (result == null) 
			result = getFirstImageStream(path, defaultPattern);
		 
		return result;
	}
	
	public String getFirstDocument() {
		Session s = null;
		try {
			s = init(null);
			if ( s == null )
				return "failure";
            
			Node root = s.getRootNode();
            Node docs = root.getNode("default/" + path + "/otherDocs"); //product/LODGING/prueba/otherDocs
            NodeIterator ni = docs.getNodes();
            if (ni.hasNext()) {
            	Node doc = ni.nextNode().getNode("jcr:content");
	            if ( doc!=null ) 
	            	download(doc, null, null);

            }
            return "success";
        } catch (PathNotFoundException e) { 
        	LogManager.getLog(getClass()).debug(e.getMessage(), e);
        	responseError();
		} catch (IOException e) { 
			LogManager.getLog(getClass()).debug(e.getMessage(), e);
		} catch (RepositoryException e) {
			LogManager.getLog(getClass()).debug(e.getMessage(), e);
			responseError();
		} finally {
			if ( s!=null ) s.logout();
		}
		return "failure";
	}

	
	public String getFirstImage() {
		Session s = null;
		try {
			s = init(null);
			if ( s == null )
				return "failure";
            
			Node root = s.getRootNode();
            Node docs = root.getNode("default/" + path + "/images"); //product/LODGING/prueba/otherDocs
            NodeIterator ni = docs.getNodes();
            
            TreeMap<Integer, Node> orderImages = new TreeMap<Integer, Node> (); 
			List<Node> noOrderImages = new ArrayList<Node> ();
            while (ni.hasNext()) {
            	Node image = ni.nextNode().getNode("jcr:content");
            	if ( image!=null ){
            		if (image.hasProperty("ysf:order")){
            			orderImages.put(Integer.parseInt(image.getProperty("ysf:order").getValue().getString()), image);
            		}else{
            			noOrderImages.add(image);
            		}
            	}
            }
            
            Map<String, String[]> params = getFacesContext().getExternalContext().getRequestParameterValuesMap();
    		String[] width = params.get("width");
    		String[] height = params.get("height");
    		
    		String result = null;
    		
    		if (!orderImages.isEmpty()){
    			result = getScaledImage(orderImages.firstEntry().getValue().getUUID(), width, height);
            }else if (!noOrderImages.isEmpty()){
            	result = getScaledImage(noOrderImages.get(0).getUUID(), width, height);
            }
    		
    		if ( result!=null && "success".equals(result) ) 
    			return result;
            
            if (!orderImages.isEmpty()){
            	download(orderImages.firstEntry().getValue(), width!=null?Float.valueOf(width[0]):null, height!=null?Float.valueOf(height[0]):null);
            }else if (!noOrderImages.isEmpty()){
            	download(noOrderImages.get(0), width!=null?Float.valueOf(width[0]):null, height!=null?Float.valueOf(height[0]):null);
            }
            return "success";
			
        } catch (PathNotFoundException e) { 
        	LogManager.getLog(getClass()).debug(e.getMessage(), e);
        } catch (RepositoryException e) {
			LogManager.getLog(getClass()).debug(e.getMessage(), e);
		} catch (IOException e) { 
			LogManager.getLog(getClass()).debug(e.getMessage(), e);
		} finally {
			if ( s!=null ) s.logout();
		}
		return "failure";
	}
	
	public List<JcrNodeInfo> getImages() {
		if ( images == null )
			loadAttachs();
		return images;
	}
	
	
	public String shiftImageUp (){
		return shiftImageCommon(false);
	}

	public String shiftImageDown (){
		return shiftImageCommon(true);
	}
	
	public String shiftImageCommon (boolean down){
		Session s = null;
		try {
			s = init(null);			
			if ( s==null )
				return "";
			
        	Node n1 = s.getNodeByUUID(name);
        	Node n2 = getNodeCommon(s, n1, down);
        	
        	String orderN1 = n1.getProperty("ysf:order").getValue().getString();
        	String orderN2 = n2.getProperty("ysf:order").getValue().getString();
        	
        	n1.setProperty("ysf:order", orderN2);
        	n2.setProperty("ysf:order", orderN1);
        	
        	s.save();
                        
		} catch (RepositoryException e) {
			LogManager.getLog(getClass()).error(e.getMessage(), e);
			
		} finally {
			if ( s!=null ) s.logout();
		}
		
		loadAttachs();
		return "success";
		
		
	}
	
	public Set<String> getOtherDocsKeys() {
		if ( otherDocsList == null )
			loadAttachs();
		return (otherDocsList != null ) ? otherDocsList.keySet(): new HashSet<String>(0);
	}

	/**
	 * @return the upFile
	 */
	public UploadedFile getUpFile() {
		return upFile;
	}

	/**
	 * @param upFile
	 *            the upFile to set
	 */
	public void setUpFile(UploadedFile upFile) {
		this.upFile = upFile;
	}

	/**
	 * @return the name
	 */
	public String getName() {
		return name;
	}

	/**
	 * @param name the name to set
	 */
	public void setName(String name) {
		this.name = name;
	}


	/**
	 * @return the path
	 */
	public String getPath() {
		return path;
	}

	/**
	 * @param path the path to set
	 */
	public void setPath(String path) {
		this.path = path;
	}


	/**
	 * @return the entityId
	 */
	public String getEntityId() {
		return entityId;
	}

	/**
	 * @param entityId the entityId to set
	 */
	public void setEntityId(String entityId) {
		this.entityId = entityId;
	}
	
	/**
	 * @return the selectedNodes
	 */
	public List<String> getSelectedNodes() {
		return selectedNodes;
	}


	/**
	 * @param otherDocsList the otherDocsList to set
	 */
	public void setOtherDocsList(TreeMap<String, String> otherDocsList) {
		this.otherDocsList = otherDocsList;
	}

	/**
	 * @param selectedNodes the selectedNodes to set
	 */
	public void setSelectedNodes(List<String> selectedNodes) {
		this.selectedNodes = selectedNodes;
	}

	/**
	 * @return the jcrDS
	 */
	public String getJcrDS() {
		return jcrDS;
	}

	/**
	 * @param jcrDS the jcrDS to set
	 */
	public void setJcrDS(String jcrDS) {
		this.jcrDS = jcrDS;
	}
	

}